package handler

import (
	"cargo-hub/cache"
	"cargo-hub/model"
	"cargo-hub/pkg"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	redis_key := "login_user" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误三次禁止登录",
		})
		return
	}
	var user model.User
	model.DB.Debug().Where("username=?", username).First(&user)
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户不存在",
		})
		return
	}
	if user.Password != pkg.Md5(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误三次封禁2小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": user,
	})
	return
}

func RoleNodeAdd(c *gin.Context) {
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	nid, _ := strconv.Atoi(c.PostForm("nid"))
	data := model.RoleNode{
		Rid: rid,
		Nid: nid,
	}
	err := model.DB.Debug().Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "分配失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "分配成功",
	})
	return
}

func UserRoleList(c *gin.Context) {
	uid := c.Query("uid")
	/*
		SELECT
		  *
		FROM
		  roles
		  JOIN user_roles ON roles.id = user_roles.rid
		  WHERE user_roles.uid=1
	*/
	var role []model.Role
	model.DB.Table("roles").
		Joins("JOIN user_roles ON roles.id = user_roles.rid").
		Where("user_roles.uid=?", uid).
		Debug().Find(&role)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": role,
	})
	return

}

func RoleNodeList(c *gin.Context) {
	rid := c.Query("rid")
	/*
		SELECT
		  *
		FROM
		  nodes
		  JOIN role_nodes ON nodes.id = role_nodes.nid
		  WHERE role_nodes.rid=1

	*/
	var node []model.Node
	model.DB.Table("nodes").
		Joins("JOIN role_nodes ON nodes.id = role_nodes.nid").
		Where("role_nodes.rid=?", rid).
		Debug().Find(&node)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": node,
	})
	return
}
